package cn.fz.relaxation.job.tencent;

import cn.fz.relaxation.dao.entity.RealxHotSearchDO;
import cn.fz.relaxation.job.BaseHotSearchJob;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

import static cn.fz.relaxation.common.enums.HotSearchEnum.TENCENT;

@Component
@Slf4j
public class TencentHotSearchJob extends BaseHotSearchJob {
    @XxlJob("tencentHotSearchJob")
    @Override
    protected ReturnT<String> hotSearch(String param) throws IOException {
        log.info("腾讯热搜爬虫任务开始");
        this.resourceCode = TENCENT.getCode();
        try {
            // 查询腾讯新闻热搜数据
            OkHttpClient client = new OkHttpClient().newBuilder().build();
            Request request = new Request.Builder().url("https://i.news.qq.com/gw/event/pc_hot_ranking_list?ids_hash=&offset=0&page_size=50&appver=15.5_qqnews_7.1.60&rank_id=hot").method("GET", null).build();
            Response response = client.newCall(request).execute();
            JSONObject jsonObject = JSONObject.parseObject(response.body().string());
            JSONArray array = jsonObject.getJSONArray("idlist").getJSONObject(0).getJSONArray("newslist");
            List<RealxHotSearchDO> doList = Lists.newArrayList();
            for (int i = 1, len = array.size(); i < len; i++) {
                // 获取腾讯热搜信息
                JSONObject object = (JSONObject) array.get(i);
                // 构建热搜信息榜
                RealxHotSearchDO searchDO = RealxHotSearchDO.builder().hotSearchResource(TENCENT.getCode()).build();
                // 设置知乎三方ID
                searchDO.setHotSearchId(object.getString("id"));
                // 设置文章连接
                searchDO.setHotSearchUrl(object.getString("surl"));
                // 设置文章标题
                searchDO.setHotSearchTitle(object.getString("title"));
                // 设置作者名称
                searchDO.setHotSearchAuthor(object.getString("chlname"));
                // 设置文章封面
                searchDO.setHotSearchCover(object.getString("miniProShareImage"));
                // 热搜热度
                searchDO.setHotSearchHeat(object.getString("readCount"));
                // 添加到集合
                doList.add(searchDO);
            }
            if (CollectionUtils.isEmpty(doList)) {
                log.error("没有获取到腾讯数据");
                return ReturnT.SUCCESS;
            }
            // 使用自定义的Comparator进行排序
            AtomicInteger count = new AtomicInteger(1);
            // 先判断是否为空，然后转换成数值进行比较，按照倒序排序，空值放在最后。
            doList.stream().sorted(Comparator.comparing((RealxHotSearchDO hotSearch)-> !Objects.isNull(hotSearch.getHotSearchHeat())).reversed().thenComparing(hotSearch->{
                try {
                    return Integer.parseInt(hotSearch.getHotSearchHeat());
                } catch (NumberFormatException e) {
                    // 将无法解析的字符串和空值视为最小值
                    return Integer.MIN_VALUE;
                }
                // 对解析的数值进行倒序排序
            }, Comparator.reverseOrder())).map(realxHotSearchDO -> {
                realxHotSearchDO.setHotSearchOrder(count.getAndIncrement());
                return realxHotSearchDO;
            }).forEach(searchDOList::add);
            this.saveSearchListToDBAndMap();
            log.info("获取腾讯热搜数据爬虫任务结束");
        } catch (IOException e) {
            log.error("获取腾讯数据异常", e);
        }
        return ReturnT.SUCCESS;
    }
}
